package com.lxk.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lxk.dao.TbNewsBoardMapper;
import com.lxk.pojo.TbNewsBoard;
import com.lxk.pojo.TbNewsBoardExample;
import com.lxk.service.NewsService;

@Service
public class NewsServiceImpl implements NewsService {
	@Autowired
	private TbNewsBoardMapper nbMapper;

	public TbNewsBoard getNewsById(int id) {
		TbNewsBoard news = nbMapper.selectByPrimaryKey(id);
		return news;
	}
	
	public TbNewsBoard getLastNews() {
		int maxId = nbMapper.selectMaxId();
		return getNewsById(maxId);
	}
	
	public List<TbNewsBoard> getAllNews() {
		TbNewsBoardExample example = new TbNewsBoardExample();
		TbNewsBoardExample.Criteria criteria = example.createCriteria();
		criteria.andIdIsNotNull();
		criteria.andStatusEqualTo(1);
		return nbMapper.selectByExample(example);
	}

	public List<TbNewsBoard> getLatestNews(int num) {
		List<TbNewsBoard> allNews = getAllNews();
		List<TbNewsBoard> latestNews = new ArrayList<TbNewsBoard>();
		int length = allNews.size();
		for(int i=length-1; i>=length-num; i--) {
			TbNewsBoard e = allNews.get(i);
			latestNews.add(e);
		}
		return latestNews;
	}

	public List<TbNewsBoard> searchNewsByTitle(String titleKey) {
		return nbMapper.selectByKeyword(titleKey);
	}

	public List<TbNewsBoard> getDeletedNews() {
		TbNewsBoardExample example = new TbNewsBoardExample();
		TbNewsBoardExample.Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(0);
		List<TbNewsBoard> deletedList = nbMapper.selectByExample(example);
		return deletedList;
	}

	public int falseDeleteNews(int id) {
		TbNewsBoard news = new TbNewsBoard();
		Date date = new Date();
		news.setId(id);
		news.setStatus(0);
		news.setDeleteTime(date);
		return nbMapper.updateByPrimaryKeySelective(news);	
	}

	public int trueDeleteNews(int id) {
		TbNewsBoardExample example = new TbNewsBoardExample();
		TbNewsBoardExample.Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(0);
		criteria.andIdEqualTo(id);
		return nbMapper.deleteByExample(example);
	}

	public void batchTrueDeleteNews(List<Integer> list) {
		for (Integer integer : list) {
			trueDeleteNews(integer);
		}
	}

	public int addNews(TbNewsBoard news) {
		return nbMapper.insertSelective(news);
	}
	
	public int updateNews(TbNewsBoard news) {
		return nbMapper.updateByPrimaryKeySelective(news);
	}

	public TbNewsBoard editNews(String title, String description, String picUrl, String content, String editor) {
		Date editTime = new Date();
		TbNewsBoard news = new TbNewsBoard();
		news.setTitle(title);
		news.setDescription(description);
		news.setPicUrl(picUrl);
		news.setContent(content);
		news.setEditTime(editTime);
		news.setEditor(editor);
		return news;
	}

	
}
